<?php

namespace app\admin\controller\examine;

use app\admin\model\content\Content;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\OfflineInformation;
use app\common\model\UserInfo;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 资料公开审核管理
 *
 * @icon fa fa-circle-o
 */
class ShowExamine extends Backend
{

    /**
     * ShowExamine模型对象
     * @var \app\admin\model\examine\ShowExamine
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\examine\ShowExamine;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['admin', 'user'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit)->each(function (&$value) {
                    if (!empty($value['type'])) {
                        if ($value['type'] == 1) { // 个人主页
                            $data = Db::query('SHOW FULL COLUMNS FROM mp_user_info');
                            $comment = array_column($data, 'Comment');
                            $tableFiled = (new UserInfo())->getTableFields();
                            $newsArray = [];
                            foreach ($comment as $key => $values) {
                                $newsArray[array_values($tableFiled)[$key]] = $values;
                            }
                            // 修改前
                            $originData = [];
                            foreach ($value['orign_data'] as $originKey => $originValue) {
                                if (is_array($originValue)) {
                                    $originValue = implode(',', $originValue);
                                }
                                $originData[] = $newsArray[$originKey] . '【' . $originValue . '】';
                            }
                            $value['_before'] = implode("|", $originData);
                            // 修改后
                            $newsData = [];
                            foreach ($value['new_date'] as $newKey => $newValue) {
                                if (!empty($newsArray[$newKey])) {
                                    if (is_array($newValue)) {
                                        $newValue = implode(',', $newValue);
                                    }
                                    $newsData[] = $newsArray[$newKey] . '【' . $newValue . '】';
                                }
                            }
                            $value['_after'] = implode("|", $newsData);;
                        }

                        if ($value['type'] == 2) { // 课程
                            // 修改前
                            $originData = [];
                            foreach ($value['orign_data'] as $originKey_ => $originValue_) {
                                if ($content = Content::get(['id' => $originValue_['id']])) {
                                    $status = ($originValue_['status'] == 1) ? '不公开' : '公开';
                                    $originData[] = '【标题：' . $content['title'] . '】，公开类型为：【' . $status . '】';
                                }
                            }
                            $value['_before'] = implode("|", $originData);
                            // 修改后
                            $newData = [];
                            foreach ($value['new_date'] as $newDataKey_ => $newDataValue_) {
                                if ($content = Content::get(['id' => $newDataValue_['id']])) {
                                    $status = ($newDataValue_['status'] == 1) ? '不公开' : '公开';
                                    $newData[] = '【标题：' . $content['title'] . '】，公开类型为：【' . $status . '】';
                                }
                            }
                            $value['_after'] = implode("|", $newData);;
                        }

                        if ($value['type'] == 3) { // 师资公开
                            // 修改前
                            $originData = [];
                            foreach ($value['orign_data'] as $originKey_ => $originValue_) {
                                if ($rows = OfflineInformation::get(['id' => $originValue_['id']])) {
                                    $status = ($originValue_['status'] == 1) ? '不公开' : '公开';
                                    $originData[] = '【姓名：' . $rows['username'] . '】，公开类型为：【' . $status . '】';
                                }
                            }
                            $value['_before'] = implode("|", $originData);
                            // 修改后
                            $newData = [];
                            foreach ($value['new_date'] as $newDataKey_ => $newDataValue_) {
                                if ($rows = OfflineInformation::get(['id' => $newDataValue_['id']])) {
                                    $status = ($newDataValue_['status'] == 1) ? '不公开' : '公开';
                                    $newData[] = '【姓名：' . $rows['username'] . '】，公开类型为：【' . $status . '】';
                                }
                            }
                            $value['_after'] = implode("|", $newData);;
                        }
                    }
                });

            foreach ($list as $row) {
                $row->getRelation('admin')->visible(['nickname']);
                $row->getRelation('user')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['admin_uid'] = $this->auth->id ?? 0;
        $params['note'] = empty($params['note']) ? '暂无回复~~' : $params['note'];
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            if ($params['status'] == 2) {
                if ($row['type'] == 1) { // 个人主页
                    if ($userInfo = UserInfo::get(['user_id' => $row['user_id']])) {
                        $userInfo->allowField(true)->save(['status' => 1, 'state' => 1]);
                    }
                }

                if ($row['type'] == 2) { // 课程
                    (new Content())->allowField(true)->saveAll($row['new_date'], true);
                }

                if ($row['type'] == 3) { // 师资公开
                    (new OfflineInformation())->allowField(true)->saveAll($row['new_date'], true);
                }
            }

            if ($params['status'] == 3) {
                if ($row['type'] == 1) { // 个人主页
                    if ($userInfo = UserInfo::get(['user_id' => $row['user_id']])) {
                        $userInfo->allowField(true)->save(['state' => 1]);
                    }
                }
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 一键通过
     * */
    public function adopt()
    {
        $ids = $this->request->post('ids');
        if (!$ids) {
            $this->error('请勾选至少一个需要通过的数据');
        }
        $ids = json_decode($ids, true);
        $list = collection($this->model->where(['id' => ['in', $ids]])->select())->toArray();
        $primaryId = []; // 主键ID
        $userInfo = []; // 个人主页
        $content = []; // 课程
        $offlineInformation = []; // 师资公开
        foreach ($list as $key => $value) {
            $primaryId[$key]['id'] = $value['id'];
            $primaryId[$key]['status'] = 2;
            $primaryId[$key]['note'] = '审核通过';
            if ($value['type'] == 1) { // 个人主页
                if ($uInfo = UserInfo::get(['user_id' => $value['user_id']])) {
                    $userInfo[$key]['id'] = $uInfo['id'];
                    $userInfo[$key]['status'] = 1;
                    $userInfo[$key]['state'] = 1;
                }
            }

            if ($value['type'] == 2) { // 课程
                $content = $value['new_date'];
            }

            if ($value['type'] == 3) { // 师资公开
                $offlineInformation = $value['new_date'];
            }
        }
        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->getSaveAllPk($this->model->allowField(true)->saveAll($primaryId, true));
            (new UserInfo())->allowField(true)->saveAll($userInfo, true);
            (new Content())->allowField(true)->saveAll($content, true);
            (new OfflineInformation())->allowField(true)->saveAll($offlineInformation, true);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (!$result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 一键拒绝
     * */
    public function refuse($ids = null)
    {
        $ids = json_decode($ids, true);
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }
        if (!$ids) {
            $this->error('请勾选至少一个需要通过的数据');
        }
        $params = $this->request->post('row/a');
        $list = collection($this->model->where(['id' => ['in', $ids]])->select())->toArray();
        $save = []; // 主键ID
        $userInfo = []; // 个人主页
        foreach ($list as $key => $value) {
            $save[$key]['id'] = $value['id'];
            $save[$key]['status'] = 3;
            $save[$key]['note'] = empty($params['note']) ? '' : $params['note'];
            if ($uInfo = UserInfo::get(['user_id' => $value['user_id']])) {
                $userInfo[$key]['id'] = $uInfo['id'];
                $userInfo[$key]['state'] = 1;
            }
        }
        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->getSaveAllPk($this->model->allowField(true)->saveAll($save, true));
            (new UserInfo())->allowField(true)->saveAll($userInfo, true);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (!$result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
